package com.site.common.quartz;

import com.site.common.R;
import com.site.common.SpringContextUtils;
import com.site.pojo.ScheduleJob;
import com.site.pojo.ScheduleJobLog;
import com.site.service.IScheduleJobLogService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 定时任务
 */
@DisallowConcurrentExecution//上次任务没有执行完，下次任务推迟执行
public class QuartzJob extends QuartzJobBean {

    private static Logger logger = LoggerFactory.getLogger(QuartzJob.class);

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ScheduleJob scheduleJob = (ScheduleJob) jobExecutionContext.getMergedJobDataMap().get(ScheduleJob.JOB_PARAM_KEY);
        // 获取日志服务对象Bean
        IScheduleJobLogService logService = SpringContextUtils.getBean(IScheduleJobLogService.class);
        //数据库保存执行记录
        ScheduleJobLog jobLog = ScheduleJobLog.builder().jobId(scheduleJob.getJobId()).beanName(scheduleJob.getBeanName()).params(scheduleJob.getParams()).createTime(new Date()).build();

        // 任务开始执行时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            logger.debug("任务准备执行，任务ID：" + scheduleJob.getJobId());
            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            R<?> result = (R<?>)method.invoke(target,scheduleJob.getParams());
            // 任务执行时长
            long times = System.currentTimeMillis() - startTime;
            //任务状态    0：成功    1：失败
            jobLog.setTimes((int) times);
            jobLog.setStatus(0);
            if (null != result) {
                jobLog.setStatus(result.getCode());
                jobLog.setMessage(result.getMsg());
            }
            logger.debug("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
            // 任务执行时长
            long times = System.currentTimeMillis() - startTime;
            // 任务状态    0：成功  1：失败  记录数据库
            jobLog.setTimes((int)times);
            jobLog.setStatus(1);
            jobLog.setError(e.toString().substring(0,2000));
        }finally {
            // 最终记录到数据库
            logService.insert(jobLog);
        }
    }

}
